const moment = require("moment");
const db = require("../models");
const logger = require("../utils/utils.logger").logger();
const DAO = require("../dao/DAO");
const Order = db.order;

const UserBalance = db.userBalance;
const UserBalanceRecord = db.userBalanceRecord;

// 创建一个新订单
exports.create = async (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.uid)
    return res.sendResult({ data: "", code: 605, message: "用户ID不能为空！" });
  if (pm.orderType === null)
    return res.sendResult({
      data: "",
      code: 605,
      message: "订单类型不能为空！",
    });
  if (!pm.remark)
    return res.sendResult({
      data: "",
      code: 605,
      message: "购买要求／备注信息不能为空！",
    });
  if (!pm.amount)
    return res.sendResult({ data: "", code: 605, message: "跑腿费不能为空！" });

  // Create a order
  const order = {
    orderid: `WL${moment().format("YYYYMMDDHHmmss")}`,
    uid: pm.uid,
    userName: pm.userName,
    orderType: pm.orderType,
    sourceAddress: pm.sourceAddress,
    sourcePhone: pm.sourcePhone,
    targetAddress: pm.targetAddress,
    targetPhone: pm.targetPhone,
    remark: pm.remark,
    requireTime: pm.requireTime,
    timeLong: pm.timeLong,
    amount: pm.amount,
    itemSize: pm.itemSize,
    itemCount: pm.itemCount,
    sexLimit: pm.sexLimit,
    status: "0",
    // 收货码
    reciveCode: Math.floor(
      (Math.random() + Math.floor(Math.random() * 9 + 1)) * Math.pow(10, 4 - 1)
    ),
  };

  const balance = await UserBalance.findOne({ where: { uid: pm.uid } }).then(
    (balance) => {
      return balance;
    }
  );
  if (balance && Number(balance.userBalance) < Number(pm.amount)) {
    return res.sendResultAto(null, 605, "余额不足，请充值！");
  }
  await UserBalance.update(
    { userBalance: Number(balance.userBalance) - Number(pm.amount) },
    { where: { uid: pm.uid } }
  );

  DAO.create(Order, order, async (result) => {
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(result)}`
    );
    const {
      data: { orderid },
    } = result;
    const userBalanceRecord = {
      uid: pm.uid,
      oldBalance: Number(balance.userBalance),
      amount: Number(pm.amount),
      newBalance: Number(balance.userBalance) - Number(pm.amount),
      type: 1,
      orderId: orderid,
      createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
      updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    await UserBalanceRecord.create(userBalanceRecord);
    res.sendResult(result);
  });
};

// 按时间查询最新的4条待帮忙帮单
exports.findTop4List = (req, res) => {
  const pm = req.query;
  const conditions = {
    limit: 4,
    sort: {
      prop: "createdAt",
      order: "desc",
    },
    params: {
      status: 0,
    },
  };
  DAO.list(Order, conditions, (list) => {
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(list)}`
    );
    res.sendResult(list);
  });
};

// 查询所有订单
exports.findAll = (req, res) => {
  const pm = {
    sort: {
      prop: "createdAt",
      order: "desc",
    },
  };
  DAO.list(Order, pm, (list) => {
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(list)}`
    );
    res.sendResult(list);
  });
};

// 请求接帮单
exports.reciveOrder = (req, res) => {
  const pm = req.query;
  // 请求验证
  if (!pm.orderid)
    return res.sendResult({ data: "", code: 605, message: "帮单ID不能为空！" });
  if (!pm.userId)
    return res.sendResult({ data: "", code: 605, message: "用户ID不能为空！" });
  if (!pm.userGender)
    return res.sendResult({
      data: "",
      code: 605,
      message: "用户性别不能为空！",
    });

  const updateData = {
    recivedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    status: "1",
    did: pm.userId,
  };
  Order.findOne({ where: { orderid: pm.orderid } }).then((data) => {
    if (data && !data.orderid) {
      return res.sendResult({ data: "", code: 605, message: "帮单不存在！" });
    }
    if (
      Number(data.sexLimit) !== 0 &&
      Number(data.sexLimit) !== Number(pm.userGender)
    ) {
      return res.sendResult({
        data: "",
        code: 605,
        message: "用户性别不符合接单条件！",
      });
    }
    if (data.uid === pm.userId) {
      return res.sendResult({
        data: "",
        code: 605,
        message: "不允许接自己的帮单！",
      });
    }
    DAO.update(Order, updateData, { orderid: pm.orderid }, (data) => {
      // logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
      res.sendResult(data);
    });
  });
};

// 帮单已完成
exports.finishOrder = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.orderid)
    return res.sendResult({ data: "", code: 605, message: "帮单ID不能为空！" });
  if (!pm.userId)
    return res.sendResult({ data: "", code: 605, message: "用户ID不能为空！" });
  if (!pm.reciveCode)
    return res.sendResult({
      data: "",
      code: 605,
      message: "验证码不能为空！",
    });

  const updateData = {
    finishedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    status: "2",
  };
  Order.findOne({ where: { orderid: pm.orderid } }).then((orderResult) => {
    if (!orderResult.orderid) {
      return res.sendResult({ data: "", code: 605, message: "帮单不存在！" });
    }
    if (orderResult.did !== pm.userId) {
      return res.sendResult({
        data: "",
        code: 605,
        message: "配送员ID和当前用户ID不一致！",
      });
    }
    console.log(orderResult.reciveCode)
    if (orderResult.reciveCode !== pm.reciveCode) {
      return res.sendResult({
        data: "",
        code: 605,
        message: "验证码不正确！",
      });
    }

    DAO.update(
      Order,
      updateData,
      { orderid: pm.orderid },
      async (updateResult) => {
        const balance = await UserBalance.findOne({
          where: { uid: pm.userId },
        }).then((balance) => {
          return balance;
        });

        const userBalanceRecord = {
          uid: pm.userId,
          oldBalance: Number(balance.userBalance),
          amount: Number(orderResult.amount),
          newBalance: Number(balance.userBalance) + Number(orderResult.amount),
          type: 0,
          orderId: orderResult.orderid,
          createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
          updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
        };
        await UserBalanceRecord.create(userBalanceRecord);

        await UserBalance.update(
          {
            userBalance:
              Number(balance.userBalance) + Number(orderResult.amount),
          },
          { where: { uid: pm.userId } }
        );

        res.sendResult(updateResult);
      }
    );
  });
};

// 取消帮单
exports.cancelOrder = (req, res) => {
  const pm = req.query;
  // 请求验证
  if (!pm.orderid)
    return res.sendResult({ data: "", code: 605, message: "帮单ID不能为空！" });
  if (!pm.userId)
    return res.sendResult({ data: "", code: 605, message: "用户ID不能为空！" });

  const updateData = {
    canceledAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    status: "3",
  };
  Order.findOne({ where: { orderid: pm.orderid } }).then((orderResult) => {
    if (!orderResult.orderid) {
      return res.sendResult({ data: "", code: 605, message: "帮单不存在！" });
    }
    if (orderResult.uid !== pm.userId) {
      return res.sendResult({
        data: "",
        code: 605,
        message: "只能取消自己的帮单！",
      });
    }
    console.log(orderResult.status);
    if (String(orderResult.status) !== "0") {
      return res.sendResult({
        data: "",
        code: 605,
        message: "当前订单状态不允许取消！",
      });
    }

    DAO.update(
      Order,
      updateData,
      { orderid: pm.orderid },
      async (updateData) => {
        const balance = await UserBalance.findOne({
          where: { uid: pm.userId },
        }).then((balance) => {
          return balance;
        });
        const userBalanceRecord = {
          uid: pm.userId,
          oldBalance: Number(balance.userBalance),
          amount: Number(orderResult.amount),
          newBalance: Number(balance.userBalance) + Number(orderResult.amount),
          type: 2,
          orderId: orderResult.orderid,
          createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
          updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
        };
        await UserBalanceRecord.create(userBalanceRecord);
        await UserBalance.update(
          {
            userBalance:
              Number(balance.userBalance) + Number(orderResult.amount),
          },
          { where: { uid: pm.userId } }
        );

        res.sendResult(updateData);
      }
    );
  });
};
